package com.example.controller;

import com.example.model.UserInfo;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * Description:
 * User: 阿宾
 * Date: 2025-05-06
 * Time: 08:43
 */
@RequestMapping("/trans")
@RestController
public class TransController {
    @Autowired
    private UserService userService;

    @Transactional
    @RequestMapping("/register")
    public Boolean register(UserInfo userInfo){
        //用户注册
        Integer result = userService.registerUser(userInfo);
        System.out.println("注册成功,影响行数:"+result);
        //强制程序异常
        try{
            int a = 10 / 0;
        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 异常捕获后，希望事务回滚
     * 方式1：重新抛出异常
     * @param userInfo
     * @return
     */
    @Transactional
    @RequestMapping("/register1")
    public Boolean register1(UserInfo userInfo){
        //用户注册
        Integer result = userService.registerUser(userInfo);
        System.out.println("注册成功,影响行数:"+result);
        //强制程序异常
        try{
            int a = 10 / 0;
        }catch (Exception e){
            //将异常重新抛出去
            throw e;
        }
        return true;
    }
    /**
     * 异常捕获后，希望事务回滚
     * 方式2：手动回滚事务
     * @param userInfo
     * @return
     */
    @Transactional
    @RequestMapping("/register2")
    public Boolean register2(UserInfo userInfo){
        //用户注册
        Integer result = userService.registerUser(userInfo);
        System.out.println("注册成功,影响行数:"+result);
        //强制程序异常
        try{
            int a = 10 / 0;
        }catch (Exception e){
            //手动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return true;
    }
    @Transactional
    @RequestMapping("/register3")
    public Boolean register3(UserInfo userInfo) throws IOException {
        //用户注册
        Integer result = userService.registerUser(userInfo);
        System.out.println("注册成功,影响行数:"+result);
        if(true){
            throw new IOException();
       }
        return true;
    }

    @Transactional(rollbackFor = Exception.class,isolation = Isolation.DEFAULT)
    @RequestMapping("/register4")
    public Boolean register4(UserInfo userInfo) throws IOException {
        //用户注册
        Integer result = userService.registerUser(userInfo);
        System.out.println("注册成功,影响行数:"+result);
        if(true){
            throw new IOException();
        }
        return true;
    }
}
